package com.hourses.service.impl;

import com.alibaba.fastjson2.JSON;
import com.hourses.mapper.UnitMapper;
import com.hourses.pojo.Unit;
import com.hourses.service.UnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Description:
 * @Author:LiTao
 * @Date:2025/5/6 17:10
 */
@Service
public class UnitServiceImpl implements UnitService {
    //查询所有商品单位
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public List<Unit> selectAllUnit() {
        //先看看缓存中有没有
        String allUnits = redisTemplate.opsForValue().get("allUnits");
        if (StringUtils.hasText(allUnits)){
            //有缓存
            return JSON.parseArray(allUnits,Unit.class);
        }
        //没有缓存
        //先查
        List<Unit> units = unitMapper.selectAllUnit();
        //再存入缓存
        redisTemplate.opsForValue().set("allUnits",JSON.toJSONString(units));
        return units;
    }
}
